#include <CTimer.h>
#include <math.h>

CTimer::CTimer(void)
{
	__int64 cntsPerSec = 0;
	QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
	secsPerCnt = 1.0f / (double)cntsPerSec;

	timer_start = getTimer();
	reset();
}

CTimer::~CTimer(void)
{
}

__int64 CTimer::getTimer() const
{
	__int64 currTimeStamp = 0;
	QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
	return currTimeStamp;
}

double CTimer::getRunTime() const
{
	return (double) (getTimer() - timer_start)*secsPerCnt;
}

double CTimer::deltaTime(bool reset)
{
	double delta = (double)(getTimer() - deltatime_start)*secsPerCnt;

	if(reset)
		resetDeltaTime();

	return delta;
}

bool CTimer::stopwatch(int ms, bool reset)
{
	double delta = (double) (getTimer() - stopwatch_start)*secsPerCnt * 1000;
	if (delta > ms) 
	{
		if(reset)
			resetStopWatch();

		return true;
	}
	else return false;
}

#pragma warning( disable : 4244)

//deltaSec can add an time offset
void CTimer::resetStopWatch(double deltaSec)
{
	stopwatch_start = getTimer();
	if (deltaSec > 0)
	{
		double delta = deltaSec/secsPerCnt;
		stopwatch_start -= delta;
	}
}

void CTimer::resetDeltaTime(double deltaSec)
{
	deltatime_start = getTimer();
	if (deltaSec > 0)
	{
		double delta = (double)deltaSec/secsPerCnt;
		deltatime_start -= delta;
	}
}

void CTimer::resetRunTime(double deltaSec)
{
	timer_start = getTimer();
	if (deltaSec > 0)
	{
		double delta = (double)deltaSec/secsPerCnt;
		timer_start -= delta;
	}
}


void CTimer::reset(double deltaSec)
{
	resetRunTime(deltaSec);
	resetDeltaTime(deltaSec);
	resetStopWatch(deltaSec);
}

//adds time to the timer
void CTimer::jump(double deltaSec)
{
	double newRunTime = getRunTime() + deltaSec;
	resetRunTime(newRunTime);

	double newDeltaTime = deltaTime() + deltaSec;
	resetDeltaTime(newDeltaTime);

	double newStopWatch = (double)(getTimer() - stopwatch_start)*secsPerCnt + deltaSec;
	resetStopWatch(newStopWatch);
}

#pragma warning( default : 4244)
